<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .box{
            position: relative;
            margin: 50px auto;
            width: 400px;
            height: 10px;
            background-color: green;
        }
        .bar{
            position: absolute;
            top: -5px;
            left: 0;
            width: 10px;
            height: 20px;
            background-color: red;
            /* 鼠标移入变成小手 */
            cursor: pointer;
        }
        .mask{
            position: absolute;
            top: 0;
            left: 0;
            height: 10px;
            background-color: red;
        }
        p{
            text-align: center;
            color: red;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="bar"></div>
        <div class="mask"></div>
    </div>
    <p>已经走了</p>
</body>
</html>
<script>
    //  获取
    var box = document.querySelector('.box')
    var bar = document.querySelector('.bar')
    var p = document.querySelector('p')
    var mask = document.querySelector('.mask')
    //  按下不松事件
    bar.onmousedown = function(event){
        // event兼容
        event = event || window.event
        // bar类距离left的距离
        var barleft = bar.offsetLeft
        // 鼠标点击时距离left的距离
        var intleft = event.clientX
        //  鼠标移动事件
        bar.onmousemove = function(event){
            event = event || window.event
            // 此处event.clientX指鼠标移动时的位置
            var moveX = event.clientX - intleft + barleft
            if(moveX > box.offsetWidth - bar.offsetWidth){
                moveX = box.offsetWidth - bar.offsetWidth
            }else if(moveX < 0){
                moveX = 0
            }
            //  bar类移动
            bar.style.left = moveX + 'px'
            //  mask类移动
            mask.style.width = moveX + 'px'
            //  计算百分比
            var percent = (moveX / (box.offsetWidth - bar.offsetWidth) *100).toFixed(2)
            // 不选中其他
            window.getSelection()?window.getSelection().removeAllRanges():document.selection.empty();
            p.innerHTML = '已经走了' +percent + '%';
        }
    }
    // 抬起事件
    bar.onmouseup = function(){
        //  清除
        document.onmousemove = ""
    }
</script>